<template>
  <div class="con table-gl-w">
    <div class="search-con search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" :max-num="4" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerLeft>
          <a-button class="gray-outline" size="medium" @click="importInventory.visible = true" v-if="$authPass('inventory.inventory.import')">导入初始库存</a-button>
          <a-button class="gray-outline" size="medium" style="margin: 0 10px" v-if="$authPass('inventory.inventory.updatePrice')" @click="setPrice">设置库存单价</a-button>
          <a-button class="gray-outline" size="medium" @click="setSpace" v-if="$authPass('inventory.location.bind')">更换货位</a-button>
        </template>
        <template #tableBody>
          <a-table ref="table" size="mini" class="table-two-line" v-model:selectedKeys="rowSelectList" @sorter-change="sortChange" row-key="id" :loading="loading" :summary="summary" :row-selection="rowSelection" :columns="columns" :data="tableList" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column title="序号" :width="60" fixed="left">
                <template #cell="{ record, rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column title="仓库名称" :width="140" fixed="left">
                <template #cell="{ record, rowIndex }"> {{ record.warehouseName }}({{ record.warehouseCode }}) </template>
              </a-table-column>
              <a-table-column title="店铺" :width="140" fixed="left">
                <template #cell="{ record, rowIndex }">
                  {{ record.shopName }}
                </template>
              </a-table-column>
              <a-table-column title="货主" :width="100" #cell="{ record, rowIndex }" fixed="left"> {{ record.ownerName }} </a-table-column>
              <a-table-column title="图片" :width="60" fixed="left">
                <template #cell="{ record, rowIndex }">
                  <ImgPopover :src="record.productImg">
                    <template #con>
                      <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                    </template>
                  </ImgPopover>
                </template>
              </a-table-column>
              <a-table-column title="产品名称/SKU" :width="120" fixed="left">
                <template #cell="{ record, rowIndex }">
                  <TextLimit :val="record.productName" :rows="1" />
                  <div class="flex-c">
                    <div style="width: 90px">
                      <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="1" />
                    </div>
                    <CopyText class="popup-edit-icon-hover" :val="record.sku" />
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="MSKU/FNSKU" :width="140" fixed="left">
                <template #cell="{ record, rowIndex }">
                  <div class="flex-c">
                    <TextLimit style="width: 115px" :val="record.msku || '--'" :rows="1" />
                    <CopyText v-if="record.msku" class="popup-edit-icon-hover" :val="record.msku" />
                  </div>
                  <div class="flex-c">
                    <TextLimit style="width: 115px" :val="record.fnsku || '--'" :rows="1" />
                    <CopyText v-if="record.fnsku" class="popup-edit-icon-hover" :val="record.fnsku" />
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="SPU/类目" :width="140">
                <template #cell="{ record, rowIndex }">
                  <div class="flex-c">
                    <TextLimit style="width: 115px" :val="record.spu || '--'" :rows="1" />
                    <CopyText v-if="record.spu" class="popup-edit-icon-hover" :val="record.spu" />
                  </div>
                  <p>{{ record.cateName }}</p>
                </template>
              </a-table-column>
              <a-table-column title="品牌" :width="120">
                <template #cell="{ record, rowIndex }">
                  {{ record.brandName }}
                </template>
              </a-table-column>
              <a-table-column title="单位" :width="60">
                <template #cell="{ record, rowIndex }">
                  {{ record.unitName }}
                </template>
              </a-table-column>
              <a-table-column title="产品类型" :width="120">
                <template #cell="{ record, rowIndex }">
                  {{ record.productType }}
                </template>
              </a-table-column>
              <a-table-column title="库存属性" :width="80">
                <template #cell="{ record, rowIndex }">
                  {{ record.attribute == 'good' ? '良品' : '次品' }}
                </template>
              </a-table-column>
              <a-table-column title="库位编号" :width="100" data-index="inventoryCode">
                <template #cell="{ record, rowIndex }">
                  {{ record.locationCode }}
                </template>
              </a-table-column>
              <a-table-column title="可用量" data-index="amtAvailable" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="100">
                <template #cell="{ record, rowIndex }">
                  {{ record.amtAvailable }}
                </template>
              </a-table-column>
              <a-table-column title="锁定量" data-index="amtLocked" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="100">
                <template #cell="{ record, rowIndex }">
                  {{ record.amtLocked }}
                </template>
              </a-table-column>
              <a-table-column data-index="avgPrice" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="110">
                <template #title>
                  <a-popover content="根据移动加权平均算法计算该当前当前库存的单价，用于实时计算库存货值">
                    <p>
                      <span>平均单价</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record, rowIndex }">
                  {{ record.avgPrice }}
                </template>
              </a-table-column>
              <a-table-column data-index="inventoryTotal" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="110">
                <template #title>
                  <a-popover content="在库数=可用量+锁定量+次品量">
                    <p>
                      <span>在库数</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record, rowIndex }">
                  {{ record.inventoryTotal }}
                </template>
              </a-table-column>
              <a-table-column data-index="inventoryValue" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="110">
                <template #title>
                  <a-popover content="在库货值=在库数*平均单价">
                    <p>
                      <span>在库货值</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record, rowIndex }">
                  {{ record.inventoryValue }}
                </template>
              </a-table-column>
              <a-table-column data-index="amtPlan" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="110">
                <template #title>
                  <a-popover content="计划数量是指提采购计划单还未生成采购单的数据">
                    <p>
                      <span>计划数量</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record, rowIndex }">
                  {{ record.amtPlan }}
                </template>
              </a-table-column>
              <a-table-column data-index="amtPurchase" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="110">
                <template #title>
                  <a-popover content="采购数量是指还在采购中的数量">
                    <p>
                      <span>采购量</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record, rowIndex }">
                  {{ record.amtPurchase }}
                </template>
              </a-table-column>
              <a-table-column data-index="amtToBeIn" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="110">
                <template #title>
                  <a-popover content="有入库单还没有签收的数量">
                    <p>
                      <span>待入库数</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template #cell="{ record, rowIndex }">
                  {{ record.amtToBeIn }}
                </template>
              </a-table-column>
              <a-table-column data-index="gmtCreate" title="创建时间" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="160">
                <template #cell="{ record, rowIndex }">
                  {{ $setTime(record.gmtCreate) }}
                </template>
              </a-table-column>
              <a-table-column data-index="gmtWrite" title="库存更新时间" :sortable="{ sortDirections: ['ascend', 'descend'] }" :width="160">
                <template #cell="{ record, rowIndex }">
                  {{ $setTime(record.gmtWrite) }}
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="60" fixed="right">
                <template #cell="{ record, rowIndex }">
                  <a-button type="text" size="mini" @click="show(record)">详情</a-button>
                </template>
              </a-table-column>
            </template>
            <template #summary-cell="{ column, record, rowIndex }">
              <div>{{ record[column.dataIndex] }}</div>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <ImportVentory ref="importInventory" @save="sizeChange(20)" />
  <SetInventoryPrice ref="setInventpryPrice" @save="save" :list="rowSelectItems" />
  <AdjustSpace ref="adjustSpace" @save="save" :list="rowSelectItems" />
  <ShowDetail ref="showDetail" :info="detailInfo" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import TableWrap from '@/components/TableWrap.vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { findWarehouseListByParam, findShopListByShare } from '@/api/warehouse'
  import { findInventoryPage, findInventorySum } from '@/api/inventory'
  import { getCategoryList } from '@/api/product'
  import { getOrganizesUser } from '@/api/system'
  import ImportVentory from './components/importInventory.vue'
  import SetInventoryPrice from './components/setInventpryPrice.vue'
  import AdjustSpace from './components/adjustSpace.vue'
  import ShowDetail from './components/showDetail.vue'
  import _ from 'lodash-es'
  import { Message } from '@arco-design/web-vue'
  import useClipboard from 'vue-clipboard3'

  export default defineComponent({
    components: { TableWrap, FilterTable, ImportVentory, SetInventoryPrice, AdjustSpace, ShowDetail },
    setup() {
      const importInventory = ref()
      const setInventpryPrice = ref()
      const adjustSpace = ref()
      const showDetail = ref()
      const table = ref()
      const { toClipboard } = useClipboard()
      const data: any = reactive({
        loading: false,
        searchValue: {
          sortField: '',
          sortType: '',
        },
        tableList: [],
        filterItem: [
          {
            key: 'warehouseCodes',
            label: '仓库名称',
            value: ref(),
            type: 'select_multiple',
            width: 160,
            optionItems: [],
          },
          {
            key: 'shopIds',
            label: '选择店铺',
            value: ref(),
            type: 'select_multiple',
            width: 160,
            optionItems: [],
          },
          {
            key: 'ownerIds',
            label: '选择货主',
            value: ref(),
            type: 'select_multiple',
            width: 160,
            optionItems: [],
          },
          {
            type: 'input_keyword',
            key: 'skus',
            keyItems: [
              { label: 'SKU', value: 'skus' },
              { label: 'SPU', value: 'spus' },
              { label: 'MSKU', value: 'mskus' },
              { label: 'FNSKU', value: 'fnskus' },
              { label: '产品名称', value: 'productName' },
            ],
            keyWidth: '90',
            value: ref(),
            placeholder: '请输入',
            label: 'SKU',
            width: 180,
            isMultiple: true,
          },
          {
            type: 'cascader',
            key: 'cateId',
            optionItems: [],
            keyWidth: '120',
            value: ref(),
            placeholder: '请选择',
            label: '类目',
            width: '100%',
            isMultiple: true,
          },
          {
            key: 'amtType',
            label: '库存数',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: [
              { label: '全部', value: '' },
              { label: '可用数>0', value: '1' },
              { label: '可用数=0', value: '0' },
              // { label: '不良品数>0', value: '3' },
              // { label: '不良品数=0', value: '4' },
            ],
          },
          {
            key: 'price',
            label: '库存单价',
            value: ref([]),
            type: 'num_range',
            width: '80',
            optionField: {
              //最小值和最大值的转换
              min: 'priceMin',
              max: 'priceMax',
            },
          },
          {
            key: 'attribute',
            label: '库存属性',
            value: ref(),
            type: 'select',
            width: '100%',
            optionItems: [
              { label: '全部', value: '' },
              { label: '良品', value: 'good' },
              { label: '次品', value: 'defective' },
            ],
          },
        ],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
        },
        rowSelectList: [],
        rowSelectItems: [],
        detailInfo: {},
        summartData: {},
      })
      const summary = () => {
        let obj = {
          amtAvailable: 0,
          amtLocked: 0,
          inventoryTotal: 0,
          inventoryValue: 0,
        }

        obj.amtAvailable = data.summartData?.amtAvailable || 0
        obj.amtLocked = data.summartData?.amtLocked || 0
        obj.inventoryTotal = data.summartData?.inventoryTotal || 0
        obj.inventoryValue = data.summartData?.inventoryValue || 0

        return [
          {
            inventoryCode: '合计',
            ...obj,
          },
        ]
      }

      const searchByVal = (info: any) => {
        let obj = _.cloneDeep(info)
        data.searchValue = {}
        data.searchValue = Object.assign(data.searchValue, obj)
        delete data.searchValue.price
        data.pageNation.pageNum = 1
        getList()
        getSummartData()
      }

      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }

      const sortChange = (item: any, extra: any) => {
        if (extra) {
          data.searchValue.sortField = item
          data.searchValue.sortType = extra == 'ascend' ? '1' : '-1'
        } else {
          data.searchValue.sortField = ''
          data.searchValue.sortType = ''
        }
        getList()
      }

      const selectColumn = (val: any) => {
        data.rowSelectList = val
        data.rowSelectItems = []
        val.forEach((e: any) => {
          let obj = data.tableList.find((el: any) => e == el.id)
          data.rowSelectItems.push(obj)
        })
      }

      const getList = async () => {
        let params = {
          ...data.searchValue,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        const res: any = await findInventoryPage(params)
        if (res.code == 'SUCCESS') {
          data.tableList = res.data.records
          data.pageNation.total = res.data.total
        }
        data.loading = false
      }
      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.warehouseName
          e.value = e.warehouseCode
        })
        data.filterItem[0].optionItems = arr
      }

      const getShopListByShare = async () => {
        const res = await findShopListByShare()
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.shopName
          e.value = e.sellerMarketId
        })
        data.filterItem[1].optionItems = arr
      }

      // 获取人员
      const getUserList = async () => {
        let params = {
          depart: false,
          needRole: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res = await getOrganizesUser(params)
        let arr = res?.data?.records || []
        arr.map((e: any) => {
          e.label = e.userName
          e.value = e.id
        })
        data.filterItem[2].optionItems = arr
      }

      const getCategory = async () => {
        const res: any = await getCategoryList()
        data.filterItem[3].optionItems = res.data
      }
      const show = (info: any) => {
        data.detailInfo = info
        showDetail.value.visible = true
      }

      const setPrice = () => {
        if (data.rowSelectList.length <= 0) {
          return Message.error('请先选择需要操作的数据')
        }
        selectColumn(data.rowSelectList)
        setInventpryPrice.value.visible = true
      }

      const setSpace = () => {
        if (data.rowSelectList.length <= 0) {
          return Message.error('请先选择需要操作的数据')
        }

        selectColumn(data.rowSelectList)

        let arr: any = []
        data.rowSelectItems.forEach((e: any) => {
          if (arr.indexOf(e.warehouseCode) == -1) {
            arr.push(e.warehouseCode)
          }
        })

        if (arr.length > 1) {
          return Message.error('只能选择相同仓库的数据')
        }

        adjustSpace.value.visible = true
      }

      const getSummartData = async () => {
        let params = {
          ...data.searchValue,
        }
        const res = await findInventorySum(params)
        data.summartData = res?.data || {}
      }

      const save = () => {
        data.rowSelectList = []
        getList()
      }

      const copy = async (val: string) => {
        try {
          // 复制
          await toClipboard(val)
          Message.success('复制成功')
          // 复制成功
        } catch (e) {
          // 复制失败
        }
      }

      getSummartData()
      getWareHouseList()
      getShopListByShare()
      getCategory()
      getList()
      getUserList()
      return {
        ...(toRefs(data) as any),
        searchByVal,
        changePage,
        sizeChange,
        selectColumn,
        summary,
        sortChange,
        importInventory,
        setInventpryPrice,
        adjustSpace,
        showDetail,
        show,
        getList,
        setPrice,
        setSpace,
        save,
        table,
        copy,
      }
    },
  })
</script>

<style lang="less" scoped>
  .icon-box {
    &:hover i {
      display: inline-block;
    }

    i {
      display: none;
    }
  }
</style>
